package ru.gerunn.silent.client;

import java.io.IOException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import ru.gerunn.silent.common.ConsoleReader;
import ru.gerunn.silent.common.ConsoleWriter;
import ru.gerunn.silent.common.RWThread;
import ru.gerunn.silent.common.Reader;
import ru.gerunn.silent.common.SSLSocketReader;
import ru.gerunn.silent.common.SSLSocketWriter;
import ru.gerunn.silent.common.Writer;

public class Client implements Runnable {

	private int port;

	public Client() {
		this.setPort(8883);
	}

	public Client(int port) {
		this.setPort(port);
	}

	public void run() {
		try {
			System.setProperty("javax.net.ssl.trustStore", "keystore.jks");
			System.setProperty("javax.net.ssl.trustStorePassword", "Hjz3&5");

			SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
			SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", this.getPort());
			socket.startHandshake();

			Writer socketWriter = new SSLSocketWriter(socket);
			Reader socketReader = new SSLSocketReader(socket);
			Writer consoleWriter = new ConsoleWriter();
			Reader consoleReader = new ConsoleReader();

			Thread csRW = new Thread(new RWThread(consoleReader, socketWriter));
			Thread scRW = new Thread(new RWThread(socketReader, consoleWriter));

			csRW.start();
			scRW.start();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(0);
		}
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}
